<template>
	<input type="text" v-model="state.userMessage" v-on:keypress="txtMsgOnkeypress" />
	<div>
		<!-- <ul>
			<li v-for="(msg,index) in state.messages" :key="index">{{msg}}</li>
		</ul> -->
	</div>
	<el-button type="primary">Primary</el-button>
	<el-button type="success">Success</el-button>
	<el-button type="info">Info</el-button>
	<el-button type="warning">Warning</el-button>
	<el-button type="danger">Danger</el-button>
</template>

<script setup>
	import {
		ref
	} from 'vue'
	import {
		reactive,
		onMounted
	} from 'vue'
	import * as signalR from '@microsoft/signalr'

	defineProps({
		msg: String
	})

	var connection
	const state = reactive({
		userMessage: "",
		messages: []
	})

	async function start() {
		try {
			await connection.start();
			console.log("连接成功.");
		} catch (err) {
			console.log(err);
			setTimeout(start, 5000);
		}
	};

	const count = ref(0)
	onMounted(async () => {
		console.log(1)


		connection = new signalR.HubConnectionBuilder()
			.withUrl('/Hubs/ChatRoomHub') //https://localhost:7295/Hubs
			.build(); //withAutomaticReconnect()   
		connection.onclose(async () => {
			await start();
		});
		start();
		console.log(2)

		console.log(3)
		// connection.invoke("ReceivePublicMessage").catch(function(err) {
		// 	return console.error(err.toString());
		// });

		connection.on('SendPublicMessage', msg => {
			console.log(msg)
			state.messages.push(msg);
			console.log(4)
		});

	});
	const txtMsgOnkeypress = async function(e) {
		console.log(5)
		//connection.start();
		//if (e.keyCode != 13) return;
		//state.userMessage = "123"
		connection.invoke("SendPublicMessage", state.userMessage);
		//state.userMessage = "";
	}
</script>

<style scoped>
	a {
		color: #42b983;
	}
</style>
